<template>
  <div class="chatroom-container">
    <!-- 头部 -->
    <div class="chat-header">
      <el-icon :size="20" class="back-icon" @click="goBack">
        <ArrowLeft />
      </el-icon>
      <div class="header-info">
        <h1>客服工作台</h1>
        <span :class="['online-status', isOnline ? 'status-online' : 'status-offline']">
          {{ isOnline ? '在线' : '离线' }}
        </span>
      </div>
      <div class="header-right"></div>
    </div>

    <!-- 聊天内容区 -->
    <div class="chat-content" ref="chatContentRef">
      <div class="message-list">
        <!-- 欢迎消息 -->
        <div class="welcome-message">
      <div class="welcome-avatar">
        <el-icon :size="28"><Service /></el-icon>
      </div>
          <div class="welcome-text">
            <h3>客服工作台</h3>
            <p>等待用户咨询中...</p>
          </div>
        </div>

        <!-- 消息列表 -->
        <div 
          v-for="(msg, index) in messages" 
          :key="index"
          :class="['message-item', msg.type === 'service' ? 'message-right' : 'message-left']"
        >
          <!-- 用户消息（左边） -->
          <template v-if="msg.type === 'user'">
            <div class="message-avatar user-avatar">
              <el-icon :size="20"><User /></el-icon>
            </div>
            <div class="message-wrapper">
              <div class="message-info">
                <span class="message-name">用户</span>
                <span class="message-time">{{ msg.time }}</span>
              </div>
              <div class="message-bubble service-bubble">
                {{ msg.content }}
              </div>
            </div>
          </template>

          <!-- 客服消息（右边，我发的） -->
          <template v-else>
            <div class="message-wrapper">
              <div class="message-info">
                <span class="message-time">{{ msg.time }}</span>
                <span class="message-name">我</span>
              </div>
              <div class="message-bubble user-bubble">
                {{ msg.content }}
              </div>
            </div>
            <div class="message-avatar">
              <el-icon :size="20"><Service /></el-icon>
            </div>
          </template>
        </div>

        <!-- 正在输入提示 -->
        <div v-if="isTyping" class="typing-indicator">
          <div class="message-avatar">
            <el-icon :size="20"><Service /></el-icon>
          </div>
          <div class="typing-dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区 -->
    <div class="chat-input-area">
      <div class="input-wrapper">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="1"
          :autosize="{ minRows: 1, maxRows: 4 }"
          placeholder="请输入您的问题..."
          @keydown.enter.exact="handleEnter"
          class="message-input"
        />
        <el-button 
          type="primary" 
          :disabled="!inputMessage.trim()"
          @click="sendMessage"
          class="send-button"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft, 
  Service, 
  User,
  List
} from '@element-plus/icons-vue'

const router = useRouter()
const chatContentRef = ref(null)
const inputMessage = ref('')
const messages = ref([])
const isOnline = ref(false)
const isTyping = ref(false)
const showQuickReplies = ref(true)

// WebSocket 相关
let websocket = null
const reconnectTimeout = ref(null)
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 5

// 快捷回复列表
const quickReplies = ref([
  { id: 1, text: '如何预约教练？' },
  { id: 2, text: '如何进行实名认证？' },
  { id: 3, text: '预约成功后如何联系教练？' },
  { id: 4, text: '可以取消预约吗？' },
  { id: 5, text: '忘记密码怎么办？' },
  { id: 6, text: '如何修改个人资料？' }
])

// 自动回复内容映射
const autoReplies = {
  '如何预约教练？': '您可以在"教练"页面浏览所有教练信息，点击心仪的教练进入详情页，然后点击"立即预约"按钮。填写预约信息后提交，等待教练确认即可。',
  '如何进行实名认证？': '进入"我的"页面，点击"实名认证"，按照提示填写真实姓名和身份证号码，上传身份证正反面照片。提交后我们会在1-3个工作日内完成审核。',
  '预约成功后如何联系教练？': '预约成功后，您可以在"动态"页面的预约记录中查看教练联系方式，也可以通过站内消息与教练沟通。',
  '可以取消预约吗？': '可以的。在预约时间24小时前取消不收取任何费用。在"动态"页面找到对应的预约记录，点击"取消预约"即可。24小时内取消可能会产生违约费用。',
  '忘记密码怎么办？': '在登录页面点击"忘记密码"，输入您的手机号，通过短信验证码即可重置密码。如有问题请联系客服协助处理。',
  '如何修改个人资料？': '进入"我的"页面，点击个人头像或"编辑资料"按钮，即可修改昵称、头像、性别等个人信息。',
  'default': '感谢您的咨询，客服人员会尽快为您解答。您也可以直接拨打客服热线 400-123-4567 获取帮助。'
}

const goBack = () => {
  router.back()
}

const getCurrentTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

const scrollToBottom = () => {
  nextTick(() => {
    if (chatContentRef.value) {
      chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
    }
  })
}

// WebSocket 连接函数
const connectWebSocket = () => {
  try {
    // 获取用户信息（假设存储在 localStorage）
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userId = userInfo.id || 'user_' + Date.now()
    
    // 连接到业务端后台的 WebSocket (端口 8000)
    const wsUrl = `ws://localhost:8000/api/customer-service/ws/service1`
    websocket = new WebSocket(wsUrl)
    
    websocket.onopen = () => {
      console.log('✅ WebSocket 已连接')
      isOnline.value = true
      reconnectAttempts.value = 0
      ElMessage.success('已连接到客服')
    }
    
    websocket.onmessage = (event) => {
      const messageData = {
    type: 'user',
    from_id: userId+'',
    to_id: 'service1',
    content: event.data,
    timestamp: new Date().toISOString()
  }
  messages.value.push(messageData)
    }
    
    websocket.onerror = (error) => {
      console.error('❌ WebSocket 错误:', error)
      isOnline.value = false
      ElMessage.error('连接客服失败')
    }
    
  } catch (error) {
    console.error('连接失败:', error)
    ElMessage.error('连接客服失败')
  }
}

// 关闭 WebSocket 连接
const closeWebSocket = () => {
  if (reconnectTimeout.value) {
    clearTimeout(reconnectTimeout.value)
  }
  if (websocket) {
    websocket.close()
    websocket = null
  }
}

const sendMessage = () => {
  
  if (inputMessage.value.trim() === '') {
    return 
  }
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  const userId = userInfo.id || 'user_' + Date.now()
  const messageData = {
    type: 'admin_to_user',
    from_id: 'service1',
    to_id: userId+'',
    content: inputMessage.value.trim(),
    timestamp: new Date().toISOString()
  }
  messages.value.push( {
    type: 'service',
    from_id: userId+'',
    to_id: 'service1',
    content: inputMessage.value.trim(),
    timestamp: new Date().toISOString()
  })
  websocket.send(JSON.stringify(messageData))
  
  // 清空输入框
  inputMessage.value = ''
}

const handleEnter = (e) => {
  if (!e.shiftKey) {
    e.preventDefault()
    sendMessage()
  }
}

const toggleQuickReplies = () => {
  showQuickReplies.value = !showQuickReplies.value
}

const selectQuickReply = (item) => {
  inputMessage.value = item.text
  showQuickReplies.value = false
  // 自动发送
  nextTick(() => {
    sendMessage()
  })
}

// 初始化
onMounted(() => {
  // 连接 WebSocket
  connectWebSocket()
})

// 清理
onUnmounted(() => {
  closeWebSocket()
})
</script>

<style scoped>
.chatroom-container {
  height: 100%;
  max-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  overflow: hidden;
  box-sizing: border-box;
}

/* 头部样式 */
.chat-header {
  background: white;
  padding: 0 16px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  z-index: 100;
  flex-shrink: 0;
}

.back-icon {
  cursor: pointer;
  color: #606266;
  transition: color 0.3s;
  padding: 4px;
}

.back-icon:hover {
  color: #409eff;
}

.header-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.header-info h1 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.online-status {
  font-size: 11px;
}

.status-online {
  color: #67c23a;
}

.status-offline {
  color: #909399;
}

.header-right {
  width: 28px;
}

/* 聊天内容区 */
.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 12px;
  scroll-behavior: smooth;
  min-height: 0;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 欢迎消息 */
.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 20px 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 8px;
}

.welcome-avatar {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.welcome-text {
  text-align: center;
}

.welcome-text h3 {
  margin: 0 0 6px 0;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.welcome-text p {
  margin: 0;
  font-size: 13px;
  color: #909399;
}

/* 消息项 */
.message-item {
  display: flex;
  gap: 10px;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-left {
  justify-content: flex-start;
}

.message-right {
  justify-content: flex-end;
}

.message-avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.user-avatar {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.message-wrapper {
  display: flex;
  flex-direction: column;
  max-width: 70%;
  gap: 6px;
}

.message-info {
  display: flex;
  gap: 6px;
  align-items: center;
  padding: 0 6px;
}

.message-right .message-info {
  justify-content: flex-end;
}

.message-name {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.message-time {
  font-size: 12px;
  color: #c0c4cc;
}

.message-bubble {
  padding: 12px 14px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.service-bubble {
  background: white;
  color: #303133;
  border-top-left-radius: 4px;
}

.user-bubble {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-top-right-radius: 4px;
}

/* 正在输入提示 */
.typing-indicator {
  display: flex;
  gap: 10px;
  align-items: center;
}

.typing-dots {
  background: white;
  padding: 12px 14px;
  border-radius: 12px;
  border-top-left-radius: 4px;
  display: flex;
  gap: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.typing-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #c0c4cc;
  animation: typing 1.4s infinite;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 快捷回复 */
.quick-replies {
  background: white;
  border-top: 1px solid #e4e7ed;
  padding: 12px;
  max-height: 140px;
  overflow-y: auto;
  flex-shrink: 0;
}

.quick-replies-title {
  font-size: 11px;
  color: #909399;
  margin-bottom: 8px;
  font-weight: 500;
}

.quick-replies-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-reply-item {
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 14px;
  font-size: 12px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.quick-reply-item:hover {
  background: #ecf5ff;
  color: #409eff;
  border-color: #409eff;
}

/* 输入区 */
.chat-input-area {
  background: white;
  border-top: 1px solid #e4e7ed;
  padding: 10px 12px;
  flex-shrink: 0;
  /* 确保输入区域始终可见 */
  min-height: fit-content;
}

.input-toolbar {
  margin-bottom: 8px;
  display: flex;
  gap: 8px;
}

.input-wrapper {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
}

:deep(.message-input .el-textarea__inner) {
  border-radius: 10px;
  padding: 10px 12px;
  font-size: 14px;
  resize: none;
  line-height: 1.5;
}

.send-button {
  height: 36px;
  padding: 0 20px;
  font-size: 14px;
}

/* 滚动条样式 */
.chat-content::-webkit-scrollbar {
  width: 6px;
}

.chat-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}

.quick-replies::-webkit-scrollbar {
  height: 4px;
}

.quick-replies::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 2px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .message-wrapper {
    max-width: 75%;
  }
  
  .quick-reply-item {
    font-size: 13px;
    padding: 8px 12px;
  }
}
</style>

